/*
 * @Author: lihaogn
 * @Date: 2021-12-21 16:45:08
 * @LastEditTime: 2022-05-25 16:02:11
 * @LastEditor: lihaogn
 * @Description: 权限模块
 * @FilePath: \lix-admin-client-vue2\src\store\modules\permission.js
 */
import { publicRoutes, privateRoutes } from '@/router'

export default {
  namespaced: true,
  state: {
    // 路由表：初始拥有静态路由权限
    routes: publicRoutes
  },
  mutations: {
    /**
     * @author: lihaogn
     * @Date: 2021-12-23 10:00:03
     * @description: 增加路由
     * @param {*} state
     * @param {*} newRoutes - 新路由
     * @return {*}
     */

    setRoutes(state, newRoutes) {
      // 永远在静态路由的基础上增加新路由
      state.routes = [...publicRoutes, ...newRoutes]
    }
  },
  actions: {
    /**
     * @author: lihaogn
     * @Date: 2021-12-21 22:21:12
     * @description: 根据权限筛选路由
     * @param {*} context
     * @param {*} pagePermissions:Array - 页面权限
     * @return {*} 路由数组
     */
    filterRoutes(context, pagePermissions) {
      const routes = []

      if (pagePermissions === false) {
        privateRoutes.forEach(page => {
          routes.push(page)
        })
      } else {
        pagePermissions.forEach(page => {
          routes.push(...privateRoutes.filter(x => x.name === page.mark))
        })
      }

      // 把 404 添加到最后
      routes.push({
        path: '/*',
        redirect: '/404'
      })

      context.commit('setRoutes', routes)

      return routes
    }
  }
}
